package scitc.alumni.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import scitc.alumni.service.Impl.UserAuthService;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Resource
    JwtUtil jwtUtil;

    @Resource
    UserAuthService userAuthService;

    @Resource
    private ObjectMapper objectMapper;

    // 需要排除的接口
    private List<String> urls = Arrays.asList(
            "/user/authorize",
            "/swagger-ui",
            "/v3/api-docs"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //??? 需要放过的url，如 登录认证，注册等
        // 获取当前url
        final String url = request.getRequestURI();
        if(urls.stream().anyMatch(path -> url.contains(path))){
            filterChain.doFilter(request,response);
            return;
        }
        // 从请求头获取token
        String token = request.getHeader("Authorization");
        if(token == null || token.isEmpty()){
            // 给用户提醒
            response.getWriter().write("Token missing！");
            response.setStatus(401);
            return;
        }
        // token是否可用
        try {
            // 取出token
            token = token.substring(7);
            log.info("token:"+token);
            Claims claims = jwtUtil.checkToken(token);

            if(claims == null){
                throw new Exception("Token Error");

            }

            // 从载荷中获取用户名和角色
            String username = claims.get("username").toString();
            String role = claims.get("role").toString();

            // 认证 （需要用户认证服务类）
            UserDetails userDetails = userAuthService.loadUserByUsername(username);
            if(userDetails==null){
                throw new Exception("用户名 错误");
            }else{
                //????????
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }catch (Exception e){
            response.getWriter().write("Token 丢失");
            response.setStatus(401);
            return;
        }

        filterChain.doFilter(request, response);
    }
}
















